#!/usr/bin/env bash

# This file is a symlink from 'tmux-test' plugin.
# You probably don't want to edit it.

# Run this script when running a test suite.

# For each virtual machine where tests run, this script performs the following:
# - starts VM
# - starts the test suite witin a VM
# - stops the VM after the test suite is done

export BOXES=""
export FILES=""
export KEEP_RUNNING=""

# global variable for script exit value
export EXIT_VALUE=0

display_help() {
	echo "Usage:"
    echo "  ./run_tests                      # runs tests on default VM ubuntu"
	echo "  ./run_tests -m ubuntu            # runs tests on ubuntu VM"
	echo "  ./run_tests -m ubuntu -m centos  # runs tests on ubuntu and cents VMs"
	echo "  ./run_tests tests/some_test      # run a single test file"
	echo "  ./run_tests --keep-running       # don't stop vagrant after the tests are done"
}

parse_arguments() {
	while :
	do
		case "$1" in
		-m | --machine)
			local machine="$2"
			if [ "$machine" == "ubuntu" ] || [ "$machine" == "centos" ]; then
				BOXES="$BOXES $machine"
			else
				echo "Unknown machine '$machine'"
				echo ""
				display_help
				exit 1
			fi
			shift 2
			;;

		-k | --keep-running)
			KEEP_RUNNING="true"
			shift
			;;

		-h | --help)
			display_help
			exit 0
			;;

		--) # End of all options
			shift
			FILES="$*"
			break
			;;

		-* )
			echo "Error: Unknown option: $1" >&2
			echo ""
			display_help
			exit 1
			;;

		*)  # No more options
			FILES="$*"
			break
			;;
		esac
	done

	# default options
	if [ -z "$BOXES" ]; then
		BOXES="ubuntu"
	fi
}

register_failing_tests() {
	EXIT_VALUE=1
}

run_vagrant() {
	local box="$1"
	VAGRANT_CWD=lib/tmux-test/ vagrant up "$box"
}

# Halt vagrant after tests are done running, unless `--keep-running`
# option is given
stop_vagrant() {
	local box="$1"
	if [ -z "$KEEP_RUNNING" ]; then
		VAGRANT_CWD=lib/tmux-test/ vagrant halt "$box"
	else
		echo
		echo "--keep-running option set, Vagrant not halted"
	fi
}

run_tests() {
	local box="$1"
	local test_file="/vagrant/tests/run_tests_in_isolation"
	echo "Running test suite on $box from: $test_file"
	echo
	VAGRANT_CWD=lib/tmux-test/ vagrant ssh "$box" -c "cd /vagrant; $test_file $FILES"
}

exit_message() {
	local exit_val="$1"
	echo
	if [ "$exit_val" == 0 ]; then
		echo "Success, tests pass!"
	else
		echo "Tests failed!" 1>&2
	fi
}

run_tests_on_vm() {
	local vm="$1"
	run_vagrant "$vm"
	run_tests "$vm"
	local tests_exit_value="$?"
	stop_vagrant "$vm"
	if [ "$tests_exit_value" -gt 0 ]; then
		register_failing_tests
	fi
}

run_tests_on_virtual_machines() {
	local box
	for box in $BOXES; do
		run_tests_on_vm "$box"
	done
}

main() {
	parse_arguments "$@"
	run_tests_on_virtual_machines
	exit_message "$EXIT_VALUE"
	exit "$EXIT_VALUE"
}
main "$@"
